﻿using System;
using System.Net.Http.Json;
using System.Reflection.Metadata;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace ThirdClient
{
	internal class Program
	{
		static async Task Main(string[] args)
		{
			var token = await GetToken();
			var getResult = await Get(token);
			Console.WriteLine("get请求结果：" + getResult);
			Thread.Sleep(1000);
			var postResult = await Post(token);
			Console.WriteLine("post请求结果：" + postResult);
			Thread.Sleep(1000);
			getResult = await Get(token);
			Console.WriteLine("get请求结果：" + getResult);
			Thread.Sleep(1000);
			postResult = await Post(token);
			Console.WriteLine("post请求结果：" + postResult);
			Console.WriteLine("Hello, World!");
		}

		static async Task<string> Post(string token)
		{
			HttpClient client = new HttpClient();
			var nonce = new Random().Next().ToString();
			var appKey = "etcp";
			var timeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); // Unix 时间戳（秒）

			client.DefaultRequestHeaders.Add("AppKey", appKey);
			client.DefaultRequestHeaders.Add("TimeStamp", timeStamp.ToString());
			client.DefaultRequestHeaders.Add("Nonce", nonce);

			IDictionary<string, string> sortedParams = new SortedDictionary<string, string>
			{
				{ "id", "1" },
				{ "name", "张三" }
			};

			IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
			StringBuilder query = new StringBuilder();
			while (dem.MoveNext())
			{
				string key = dem.Current.Key;
				string value = dem.Current.Value;
				if (!string.IsNullOrEmpty(key))
				{
					query.Append(key).Append(value);
				}
			}
			string requestDataStr = query.ToString();

			var sign = Md5Helper.ComputeMd5Hash(timeStamp.ToString() + nonce.ToString() + appKey.ToString()
				+ token.ToString() + requestDataStr);
			client.DefaultRequestHeaders.Add("Sign", sign);

			var jsonContent = JsonSerializer.Serialize(sortedParams);
			var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

			var response = await client.PostAsync($"http://localhost:5203/SignProtectedAPI/PostApi", content);
			// 确保 HTTP 响应状态是成功的
			response.EnsureSuccessStatusCode();
			// 读取响应内容
			var responseBody = await response.Content.ReadAsStringAsync();
			return responseBody;

		}

		static async Task<string> Get(string token)
		{
			HttpClient client = new HttpClient();
			var nonce = 5;
			var appKey = "etcp";
			var timeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); // Unix 时间戳（秒）

			client.DefaultRequestHeaders.Add("AppKey", appKey);
			client.DefaultRequestHeaders.Add("TimeStamp", timeStamp.ToString());
			client.DefaultRequestHeaders.Add("Nonce", nonce.ToString());

			IDictionary<string, string> sortedParams = new SortedDictionary<string, string>
			{
				{ "id", "1" },
				{ "name", "张三" }
			};

			IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
			StringBuilder query = new StringBuilder();
			while (dem.MoveNext())
			{
				string key = dem.Current.Key;
				string value = dem.Current.Value;
				if (!string.IsNullOrEmpty(key))
				{
					query.Append(key).Append(value);
				}
			}
			string requestDataStr = query.ToString();

			var sign = Md5Helper.ComputeMd5Hash(timeStamp.ToString() + nonce.ToString() + appKey.ToString()
				+ token.ToString() + requestDataStr);
			client.DefaultRequestHeaders.Add("Sign", sign);

			var response = await client.GetAsync($"http://localhost:5203/SignProtectedAPI/List?{BuildQueryString(sortedParams.ToDictionary())}");
			// 确保 HTTP 响应状态是成功的
			response.EnsureSuccessStatusCode();
			// 读取响应内容
			var responseBody = await response.Content.ReadAsStringAsync();
			return responseBody;

		}

		private static string BuildQueryString(Dictionary<string, string> parameters)
		{
			return string.Join("&", parameters.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
		}

		static async Task<string> GetToken()
		{
			HttpClient client = new HttpClient();
			//获取token
			var jsonContent = "{\"appKey\":\"etcp\", \"appSecret\":\"34853399624948488e1b3cb63ea5e578\"}"; // key 与 secret提前提供
			var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
			var response = await client.PostAsync("http://localhost:5203/ThirdClient/GetToken", content);

			// 确保 HTTP 响应状态是成功的
			response.EnsureSuccessStatusCode();
			var token = await response.Content.ReadAsStringAsync();
			return token;
		}
	}
}
